package miniproj.services.data;

import java.io.*;

/**
 * 
 * This class load data serialized with the ObjectInputStream method
 * 
 * @author Baptiste Viale
 * 
 */
public class StreamDataLoader implements DataLoader {

	private String folderPath;

	/**
	 * Instantiates a new stream data loader.
	 * 
	 * @param folderPath
	 *            the folder path
	 */
	public StreamDataLoader(String folderPath) {
		this.folderPath = folderPath;
	}

	/**
	 * Load the DataContext using the java object serialization method.
	 * 
	 * @param dataContextFileName
	 *            the data context file name
	 * @return the data context loaded
	 */
	@Override
	public DataContext getDataContext(String dataContextFileName) {
		String fileFullPath = this.folderPath + "/" + dataContextFileName;

		Object loadedItem = this.loadItem(fileFullPath);

		if (loadedItem == null)
			return null;

		DataContext dc = (DataContext) loadedItem;

		return dc;
	}

	private Object loadItem(String fileFullPath) {
		Object toReturn = null;

		File f = new File(fileFullPath);
		if (!f.exists()) {
			System.err.println("No data file found at " + fileFullPath);
			return null;
		}

		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(new FileInputStream(fileFullPath));
		} catch (FileNotFoundException e) {
			System.err.println("File not found : " + fileFullPath);
			return null;
		} catch (IOException e) {
			System.err.println("Input/Output Exception while loading object : "
					+ e.getMessage());
			return null;
		}

		try {
			toReturn = ois.readObject();
			ois.close();
		} catch (IOException e) {
			System.err.println("Input/Output Exception while reading object : "
					+ e.getMessage());
		} catch (ClassNotFoundException e) {
			System.err.println(e.getMessage());
		}

		return toReturn;
	}
}
